// 引入react
import * as React from 'react';
import {StyleSheet, View, Text, Dimensions, Image, TouchableOpacity} from 'react-native';
import {CardItem} from '../../../../componet/settingComponent/CardItem';
import AllStyle from '../../../../style';
import {Agenda, CalendarProvider, ExpandableCalendar, LocaleConfig} from 'react-native-calendars';
import {BrLine} from '../../../../componet/settingComponent/BrLine';
import EvilIcons from 'react-native-vector-icons/EvilIcons';
import AntDesign from 'react-native-vector-icons/AntDesign';
import {
    getActualMonth,
    getActualMonthByUserId,
    getToDayByUserIdAndDateRecord,
    getUserToDayRecord,
} from '../../../../api/empActual';
import {getDate} from '../../../../utils/DateUtils';
import {Loading} from '../../../../utils/Loading';
import {getSignGroupInfo, getSignGroupInfoByUserId} from '../../../../api/empPlanClasses';
import {Toast} from '../../../../utils/Toast';


LocaleConfig.locales['fr'] = {
    monthNames: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
    monthNamesShort: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
    dayNames: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
    dayNamesShort: ['日', '一', '二', '三', '四', '五', '六'],
    today: '到今天',
};
LocaleConfig.defaultLocale = 'fr';

const width = Dimensions.get('window').width;

/**
 * @Description:
 * @author TangYong
 * @date 2023/2/6
 */
export class MyStatistics extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            userId:(!this.props.userId)?null:this.props.userId,
            userMonthStatisticsData: {
                average:0,
                attendanceDataList:[],
                earlyDataList:[],
                beLateDataList:[],
                lackDataList:[],
                absenteeismDataList:[],
                restDataList:[],
            },
            user: {username: ''},
            signGroup: null,
            signGroupEntity: null,
            classes: null,
            empRecords: [],
            workDuration: 0,
            dAndMVal: true,
            //calendarDate: getDate(new Date(), 'yyyy-MM-dd').toString(),
        };
    }

    //生命周期：组件挂载后
    componentDidMount() {
        this.init();
       //alert(this.props.date)
        // console.log('....', this.props);
    }

    componentDidUpdate(oldProps) {
        //console.log(this.props)
        // 比较前后props
        if (this.props != oldProps) {
            //alert()
            this.changedAndMVal(true)
        }
        //this.changedAndMVal(true)
    }

    init = () => {

        this.getDayData( (!this.props.date)?getDate(new Date(), 'yyyy-MM-dd').toString():this.props.date);
        this.getUserInfo();
        this.getMonth();

    };

    getUserInfo() {
        if (!this.props.userId){
            getSignGroupInfo().then((res) => {
                let {user, signGroup, empPlanClassesEntity} = res.data;
                this.setState({user});
                this.setState({signGroup});
                this.setState({empPlanClassesEntity});
                //console.log(res);
            }).catch((err) => {
                Toast.showWarning(err.toString())
            });
        }else {
            getSignGroupInfoByUserId(this.props.userId).then(res=>{
                let {user, signGroup, empPlanClassesEntity} = res.data;
                this.setState({user});
                this.setState({signGroup});
                this.setState({empPlanClassesEntity});
                //console.log(res);
            }).catch(err=>{
                Toast.showWarning(err.toString())
            })
        }


    }


    getMonth() {
        if (!this.props.userId){
            getActualMonth().then(res => {
                let userMonthStatisticsData =res.data;
                this.setState({userMonthStatisticsData})
                //console.log(res);
            }).catch(err => {
                Toast.showWarning(err.toString())
            });
        }else {
            getActualMonthByUserId(this.props.userId).then(res => {
                let userMonthStatisticsData =res.data;
                this.setState({userMonthStatisticsData})
                //console.log(res);
            }).catch(err => {
                Toast.showWarning(err.toString())
            })
        }


    }

    getDayData = (date) => {

        let data = {};
        // console.log(2,this.state.calendarDate)
        data.expectSignDate = date + ' 00:00:00';


        if (!this.props.userId){
            Loading.show();
            getUserToDayRecord(data).then(res => {
                Loading.hidden();
                let {classes, empRecords, workDuration} = res.data;
                workDuration = workDuration == null ? 0 : workDuration;
                this.setState({workDuration});
                this.setState({classes});
                this.setState({empRecords});
                //console.log(res.data);
                //alert(1);

            }).catch(err => {

                Loading.hidden();
                Toast.showWarning(err.toString())
            }).finally(()=>{
                Loading.hidden();
            });

        }else {
            data.userId=this.props.userId;
            getToDayByUserIdAndDateRecord(data).then(res=>{
                Loading.hidden();
                let {classes, empRecords, workDuration} = res.data;
                workDuration = workDuration == null ? 0 : workDuration;
                this.setState({workDuration});
                this.setState({classes});
                this.setState({empRecords});
            }).catch(err=>{
                Loading.hidden();
            }).finally(()=>{
                Loading.hidden();
            })
        }


    };

    onDateChanged = (date) => {
        // console.log(1,date)

        //this.setState({calendarDate: date});
        //alert('onMonthChange')
        this.getDayData(date);
    };
    onMonthChange = () => {

    };
    //方法
    goto = (name, params) => {
        console.log(name);

        const route = {
            name: name,
            params: {
                //routePathName: this.props.route.name,
                ...params,
            },

        };
        this.props.navigation.navigate(route);
    };
    changedAndMVal = (val) => {
        this.setState({dAndMVal: val});
    };


    //DOM
    render() {
        return (
            <View style={[AllStyle.card,]}>
                <View style={style.bodyTop}>
                    <View style={style.top_l}>
                        <View style={style.top_l_logo}>
                            <Text style={{color: '#fff'}}>{this.state.user.username}</Text>
                        </View>
                        <View style={style.top_l_name}>
                            <Text style={{fontSize: 18, marginBottom: 1}}>{this.state.user.username}</Text>
                            <Text
                                style={{color: '#798188'}}>{this.state.empPlanClassesEntity != null ? this.state.empPlanClassesEntity.planName : '未加入考勤组'}</Text>
                        </View>
                    </View>
                    <View style={style.top_r}>
                        <View style={style.r_container}>
                            <TouchableOpacity onPress={() => {
                                this.changedAndMVal(true);
                            }}>
                                <View style={[style.top_r_btnW, this.state.dAndMVal && {backgroundColor: '#fff'}]}>
                                    <Text>日</Text>
                                </View>
                            </TouchableOpacity>
                            <TouchableOpacity onPress={() => {
                                this.changedAndMVal(false);
                            }}>
                                <View
                                    style={[style.top_r_btnM, this.state.dAndMVal == false && {backgroundColor: '#fff'}]}>
                                    <Text>月</Text>
                                </View>
                            </TouchableOpacity>
                        </View>

                    </View>
                </View>
                <BrLine></BrLine>

                <View style={[{width: width - 60}, this.state.dAndMVal == false && {display: 'none'}]}>
                    <View style={{width: width - 60}}>
                        {
                            this.state.dAndMVal&&
                        <CalendarProvider
                             date={(!this.props.date)?getDate(new Date(), 'yyyy-MM-dd').toString():this.props.date }
                           // date={'2023-02-10'}
                            // showTodayButton
                            //  style={{height:800}}
                            //date={ITEMS[0].title}

                            onDateChanged={(date) => {
                               // alert(date)
                                //console.log(date2,'test')
                                this.onDateChanged(date);
                            }}
                            //onMonthChange={this.onMonthChange} 月份改变事件
                            // disabledOpacity={0.6}
                            // theme={{
                            //     todayTextColor: '#fff',
                            //     calendarBackground: 'red',
                            // }}
                            // todayBottomMargin={60}
                        >
                            <ExpandableCalendar
                                //initialDate={(!this.props.date)?getDate(new Date(), 'yyyy-MM-dd').toString():this.props.date }
                                // initialDate={'2023-02-11' }
                                // onDayPress={day => {
                                //     this.onDateChanged(day.dateString);
                                //     //console.log('selected day', day);
                                // }}
                                allowShadow={false}
                                pastScrollRange={3}
                                futureScrollRange={1}
                                testID={'calendars'}
                                calendarWidth={width - 60}
                                // horizontal={true}
                                openThreshold={1}
                                initialPosition={this.state.initialPosition}
                                hideArrows={true}
                                disablePan={false}
                                hideKnob={false}
                                //initialPosition={ExpandableCalendar.positions.OPEN}
                                // calendarStyle={styles.calendar}
                                // headerStyle={styles.calendar} // for horizontal only
                                //disableAllTouchEventsForDisabledDays={true}
                                //disableWeekScroll={true}
                                // theme={this.getTheme()}
                                firstDay={1}
                                // markedDates={this.getMarkedDates()}
                                // leftArrowImageSource={require('../img/previous.png')}
                                //rightArrowImageSource={require('../img/next.png')}
                            />
                        </CalendarProvider>
                        }

                    </View>
                    <BrLine></BrLine>
                    <View style={{marginTop: 10, marginBottom: 10}}>
                        <Text
                            style={style.classesText}>当日班次：{this.state.classes == null ? ' 未排班' : this.state.classes.classesName + ' ' + this.state.classes.workStartTime.toString().substring(0, 5) + '-' + this.state.classes.workEndTime.toString().substring(0, 5)}</Text>
                        <Text
                            style={style.classesText}>出勤统计：打卡{this.state.empRecords == null ? 0 : this.state.empRecords.length}次，工时{this.state.workDuration}小时</Text>
                    </View>
                    <BrLine></BrLine>
                    {this.state.empRecords != null && this.state.empRecords.length != 0 ? (
                        <View>
                            {this.state.empRecords.map((item, index) => {
                                return (
                                    <View key={index}>
                                        <View style={{marginTop: 10, marginBottom: 10}}>
                                            <View>
                                                <Text
                                                    style={(index != 0 && index != this.state.empRecords.length - 1) == false ? style.signText : style.signText2}>
                                                    {index == 0 && '上班打卡'}

                                                    {(index == this.state.empRecords.length - 1&&(this.state.empRecords.length!=1))&& '下班打卡'}
                                                    {index != 0 && index != this.state.empRecords.length - 1 && '打卡'}
                                                    {item.recordsDateTime.toString().substring(5, 16)}

                                                </Text>
                                            </View>
                                            {
                                                !(index == 0 && '上班打卡' || index == this.state.empRecords.length - 1) &&
                                                <View style={style.allText}>
                                                    <EvilIcons size={15} name={'exclamation'}
                                                               style={{color: '#798189'}}></EvilIcons>
                                                    <Text style={{color: '#798189'}}>打卡无效,此记录被更新</Text>
                                                </View>
                                            }

                                            <View style={style.allText}>
                                                <EvilIcons size={15} name={'location'}
                                                           style={{color: '#798189'}}></EvilIcons>
                                                <Text style={style.placeText}>{item.signPosition}</Text>
                                            </View>
                                            <View style={style.allText}>
                                                <EvilIcons size={15} name={'user'}
                                                           style={{color: '#798189'}}></EvilIcons>
                                                <Text style={style.faceText}>人脸验证已通过</Text>
                                            </View>

                                        </View>
                                        <BrLine></BrLine>
                                    </View>);
                            })}

                            {/*<View style={{marginTop: 10, marginBottom: 10}}>*/}
                            {/*    <View>*/}
                            {/*        <Text style={[style.signText]}>下班打卡 12.17</Text>*/}
                            {/*    </View>*/}
                            {/*    <View style={style.allText}>*/}
                            {/*        <EvilIcons size={15} name={'exclamation'}*/}
                            {/*                   style={{color: '#798189'}}></EvilIcons>*/}
                            {/*        <Text style={{color: '#798189'}}>打卡无效,此记录被更新</Text>*/}
                            {/*    </View>*/}
                            {/*    <View style={style.allText}>*/}
                            {/*        <EvilIcons size={15} name={'location'}*/}
                            {/*                   style={{color: '#798189'}}></EvilIcons>*/}
                            {/*        <Text style={style.placeText}>打卡地点</Text>*/}
                            {/*    </View>*/}
                            {/*    <View style={style.allText}>*/}
                            {/*        <EvilIcons size={15} name={'user'}*/}
                            {/*                   style={{color: '#798189'}}></EvilIcons>*/}
                            {/*        <Text style={style.faceText}>人脸验证已通过</Text>*/}
                            {/*    </View>*/}

                            {/*</View>*/}
                        </View>
                    ) : (
                        <View style={style.body_sign}>
                            <Image
                                style={style.body_sign_svg}
                                source={require('../../../../img/weijiaruGroup.png')}
                            />
                            <View style={style.body_sign_text}>
                                <Text style={{
                                    fontSize: 14,
                                    color: '#798189',
                                    marginLeft: 10,
                                }}>当日没有打卡记录</Text>
                            </View>
                        </View>
                    )}


                </View>









                <View style={[this.state.dAndMVal && {display: 'none'}]}>
                    <View style={style.mouth_Jgg}>
                        <View style={style.mouth_Jgg_one}>
                            <TouchableOpacity onPress={() => {
                                //alert(this.state.userId)
                                this.goto('userStatisticsDetails', {
                                    statsNum:0,
                                    userId:this.state.userId
                                });
                            }}>
                                <View style={style.mouth_Jgg_item}>

                                    <Text style={style.mouth_Jgg_item_num}>{this.state.userMonthStatisticsData.average}</Text>
                                    <Text style={style.mouth_Jgg_item_text}>平均工时</Text>
                                </View>

                            </TouchableOpacity>
                            <TouchableOpacity onPress={() => {
                                this.goto('userStatisticsDetails', {
                                    statsNum:1,
                                    userId:this.state.userId
                                });
                            }}>
                            <View style={style.mouth_Jgg_item}>
                                <Text style={style.mouth_Jgg_item_num}>{this.state.userMonthStatisticsData.attendanceDataList.length}</Text>
                                <Text style={style.mouth_Jgg_item_text}>出勤天数</Text>
                            </View>
                            </TouchableOpacity>
                            <TouchableOpacity onPress={() => {
                                this.goto('userStatisticsDetails', {
                                    statsNum:6,
                                    userId:this.state.userId
                                });
                            }}>
                            <View style={style.mouth_Jgg_item}>
                                <Text style={style.mouth_Jgg_item_num}>{this.state.userMonthStatisticsData.restDataList.length}</Text>
                                <Text style={style.mouth_Jgg_item_text}>休息天数</Text>
                            </View>
                            </TouchableOpacity>
                        </View>
                        <View style={style.mouth_Jgg_one}>
                            <TouchableOpacity onPress={() => {
                                this.goto('userStatisticsDetails', {
                                    statsNum:4,
                                    userId:this.state.userId
                                });
                            }}>
                            <View style={style.mouth_Jgg_item}>
                                <Text style={style.mouth_Jgg_item_num}>{this.state.userMonthStatisticsData.beLateDataList.length}</Text>
                                <Text style={style.mouth_Jgg_item_text}>迟到天数</Text>
                            </View>
                            </TouchableOpacity>
                            <TouchableOpacity onPress={() => {
                                this.goto('userStatisticsDetails', {
                                    statsNum:5,
                                    userId:this.state.userId
                                });
                            }}>
                            <View style={style.mouth_Jgg_item}>
                                <Text style={style.mouth_Jgg_item_num}>{this.state.userMonthStatisticsData.earlyDataList.length}</Text>
                                <Text style={style.mouth_Jgg_item_text}>早退天数</Text>
                            </View>
                            </TouchableOpacity>
                            <TouchableOpacity onPress={() => {
                                this.goto('userStatisticsDetails', {
                                    statsNum:3,
                                    userId:this.state.userId
                                });
                            }}>
                            <View style={style.mouth_Jgg_item}>
                                <Text style={style.mouth_Jgg_item_num}>{this.state.userMonthStatisticsData.lackDataList.length}</Text>
                                <Text style={style.mouth_Jgg_item_text}>缺卡天数</Text>
                            </View>
                            </TouchableOpacity>
                        </View>
                        <View style={style.mouth_Jgg_one}>
                            <TouchableOpacity onPress={() => {
                                this.goto('userStatisticsDetails', {
                                    statsNum:2,
                                    userId:this.state.userId
                                });
                            }}>
                            <View style={style.mouth_Jgg_item}>
                                <Text style={style.mouth_Jgg_item_num}>{this.state.userMonthStatisticsData.absenteeismDataList.length}</Text>
                                <Text style={style.mouth_Jgg_item_text}>旷工天数</Text>
                            </View>
                            </TouchableOpacity>
                        </View>
                    </View>
                    <BrLine></BrLine>
                    <TouchableOpacity onPress={() => {
                        this.goto('userStatisticsDetails', {
                            title: '个人月统计详情',
                            userId:this.state.userId
                        });
                    }}>
                        <View style={style.mouth_Jgg_select}>

                            <Text style={{color: '#798189'}}>
                                查看详情
                            </Text>


                        </View>
                    </TouchableOpacity>
                </View>
            </View>
        );
    }

}

const style = StyleSheet.create({
    //样式
    classesText: {
        marginTop: 7,
        color: '#798189',
    },
    bodyTop: {
        width: width - 60,
        marginTop: 15,
        marginBottom: 15,
        // backgroundColor: 'red',
        flexDirection: 'row',
        justifyContent: 'space-between',
    },

    top_l: {
        width: (width - 60) / 2,
        //backgroundColor: '#eee',
        flexDirection: 'row',
        // justifyContent: 'space-between',
    },
    top_l_logo: {
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#409EFF',
        borderRadius: 5,
        marginRight: 15,
        width: 45,
        height: 45,

    },
    top_l_name: {

        justifyContent: 'center',
        // alignItems: 'center',
    },

    top_r: {
        //backgroundColor:'red',
        width: (width - 60) / 2,
        justifyContent: 'center',
        alignItems: 'flex-end',
    },
    r_container: {
        backgroundColor: '#DCDFE6',
        flexDirection: 'row',
        padding: 2,
        borderRadius: 5,
    },
    top_r_btnW: {
        width: 40,
        height: 30,
        alignItems: 'center',
        justifyContent: 'center',
        borderRadius: 5,
    },
    top_r_btnM: {
        width: 40,
        height: 30,
        // backgroundColor:'#409EFF',
        justifyContent: 'center',
        alignItems: 'center',
        borderRadius: 5,

    },
    signText: {
        fontSize: 18,
        fontWeight: '400',
        marginTop: 7,
    },
    signText2: {
        fontSize: 14,
        color: '#798189',
        fontWeight: '400',
        marginTop: 7,
    },
    allText: {
        flexDirection: 'row',
        // justifyContent: 'center',
        alignItems: 'center',
        marginTop: 7,

    },
    placeText: {
        color: '#798189',
    },
    faceText: {
        color: '#798189',
    },
    body_sign: {
        alignItems: 'center',
    },
    body_sign_text: {
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        marginTop: 10,
        marginBottom: 10,
    },
    body_sign_svg: {
        flexDirection: 'row',
        //justifyContent: 'center',
        alignItems: 'center',
        width: 200,
        height: 200,
    },
    mouth_Jgg: {
        width: width - 60,
    },
    mouth_Jgg_one: {
        margin: 15,
        width: width - 60 - 30,
        flexDirection: 'row',
        justifyContent: 'space-between',
    },
    mouth_Jgg_item: {
        alignItems: 'center',
    },
    mouth_Jgg_item_num: {
        marginTop: 5,
        marginBottom: 5,
        fontSize: 20,
        fontWeight: 'bold',

    },
    mouth_Jgg_item_text: {
        color: '#798189',
    },
    mouth_Jgg_select: {
        padding: 15,
        alignItems: 'center',
    },
});
